<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div class="title">
        <div class="biaotididian">{{ agencyName }}</div>
        <div class="biaoti">责令改正情况复查记录</div>
      </div>
      <table class="tableStyle">
        <colgroup>
          <col width="15%">
          <col width="85%">
        </colgroup>
        <tbody>
          <tr>
            <td style="text-align: center; height: 35px;">当&nbsp;事&nbsp;人</td>
            <td>
              <privy-info-select-return-array v-model="form.unitName" :isTable="true" maxLength="27" return-fields="A"
                :return-array-template="[

                ]" @select="selectUnitUpdateData">
              </privy-info-select-return-array>
            </td>
          </tr>

          <tr>
            <td style="text-align: center; height: 35px;">复查时间</td>
            <td>
              <editable-textarea :text="form.time1" param-type="YYYY-MM-DD HH:mm1"
                @send-to-parent="receiveFromChild"></editable-textarea>
            </td>
          </tr>

          <tr>
            <td style="text-align: center; height: 35px;">复查地点</td>
            <td>
              <el-input v-model="form.a2" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="27" />
            </td>
          </tr>

          <tr style="height: 125px;">
            <td colspan="2" style="text-align: left;vertical-align: top; position: relative;">
              <span>现场复查情况：</span>
              <el-input type="textarea" v-model="form.a3" :rows="a3Config.maxLines"
                @keydown.native="handleKeyDown('a3', $event)" @input="handleInput('a3', $event)"
                @paste.native="handlePaste('a3', $event)" class="el-textarea-hidden"
                style="white-space: pre;overflow-x: auto;font-family: monospace;" wrap="soft" />
            </td>
          </tr>
          <tr>
            <td style="text-align: center;">
              <span>现场复查<br>凭&emsp;&emsp;证</span>
            </td>
            <td>
              <div style="display: flex; align-items: center; justify-content: center;  height: 350px;"
                class="image-container" @click="chooseImage()">
                <img v-if="!isLoading && form.imageSrc" :src="form.imageSrc" alt="现场照片"
                  style="max-height: 99%; max-width: 99%;">
                <input type="file" accept="image/*" style="display: none" ref="imageInput" @change="handleFileChange">
                <div v-if="!form.imageSrc || isLoading" class="placeholder-image" @click="chooseImage()"></div>
              </div>
            </td>
          </tr>

          <tr style="height: 50px;">
            <td colspan="2" style="text-align: left;vertical-align: top; position: relative;">
              <div
                style="position: absolute; bottom: 15px; left: 10px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  当事人签名：
                  <SignatureField label="签名1" sign-type="sign1" :img-url="form.img1"
                    @update:imgUrl="form.img1 = $event" />
                </div>
              </div>
            </td>
          </tr>

          <tr style="height: 50px;">
            <td colspan="2" style="text-align: left;vertical-align: top; position: relative;">
              <div
                style="position: absolute; bottom: 15px; left: 10px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  现场见证人签名：
                  <SignatureField label="签名2" sign-type="sign2" :img-url="form.img2"
                    @update:imgUrl="form.img2 = $event" />
                </div>
              </div>
            </td>
          </tr>

          <tr style="height: 65px;">
            <td rowspan="2" colspan="20">
              &nbsp;行政执法人员：
              <InvestigatorSelect style="width: 150px;" v-model="form.dangShiRen1" :id-field="'dangShiRenId1'"
                @change="handleInvestigatorChange" /> 执法证件号：{{ form.dangShiRenId1 }}
              <br>
              &nbsp;行政执法人员：
              <InvestigatorSelect style="width: 150px;" v-model="form.dangShiRen2" :id-field="'dangShiRenId2'"
                @change="handleInvestigatorChange" /> 执法证件号：{{ form.dangShiRenId2 }}
            </td>
          </tr>

          <tr></tr>

          <tr style="height: 100px;">
            <td style="text-align: center;">备注</td>
            <td style="text-align: left;vertical-align: top; position: relative;">
              <el-input type="textarea" v-model="form.a4" :rows="a4Config.maxLines"
                @keydown.native="handleKeyDown('a4', $event)" @input="handleInput('a4', $event)"
                @paste.native="handlePaste('a4', $event)" class="el-textarea-hidden"
                style="white-space: pre;overflow-x: auto;font-family: monospace;" wrap="soft" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js"
import PrivyInfoSelectReturnArray from "@/views/template/PrivyInfoSelectReturnArray";
import InvestigatorSelect from "@/views/template/InvestigatorSelect";
import SignatureField from "@/views/template/SignatureField";
import { createInputLimiter } from '@/utils/limitInput';

export default {
  components: { EditableTextarea, InvestigatorSelect, SignatureField, PrivyInfoSelectReturnArray},
  props: {
    currentSignType: String
  },

  data() {
    return {
      identificationNumber: '',
      resultImgurl: '',
      isLoading: false,

      currentItem: {},
      form: {},
      isPdfExport: false,
      a3Config: {
        maxLines: 4,
        charsPerLine: 32 * 2,
        maxLength: 4 * 32 * 2,
        inputLimiter: null,
        displayText: ''
      },
      a4Config: {
        maxLines: 4,
        charsPerLine: 27 * 2,
        maxLength: 4 * 27 * 2,
        inputLimiter: null,
        displayText: ''
      },
    }
  },

  created() {
    window.parent.getTemplateData((data) => {
      this.form = data;
    })
    window.postForm = () => {
      this.postForm();
    }
    this.a3Config.inputLimiter = createInputLimiter(this, {
      maxLines: this.a3Config.maxLines,
      charsPerLine: this.a3Config.charsPerLine,
      maxLength: this.a3Config.maxLength,
      propName: 'form.a3'
    });
    this.a4Config.inputLimiter = createInputLimiter(this, {
      maxLines: this.a4Config.maxLines,
      charsPerLine: this.a4Config.charsPerLine,
      maxLength: this.a4Config.maxLength,
      propName: 'form.a4'  // 直接指向form.a4
    });
  },

  mounted() {
    window.parent.changeTemplateDow();
  },

  methods: {
    // 导出为pdf
    exportPDF() {
      this.savePDF()
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `责令改正情况复查记录.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '责令改正情况复查记录.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },
    getConfigName(field) {
      switch (field) {
        case 'a4':
          return this.a4Config;
        case 'a3':
          return this.a3Config;

      }
    },
    handleKeyDown(field, e) {
      const config = this.getConfigName(field);
      config.inputLimiter.handleKeyDown(e);
    },
    handleInput(field, value) {
      const config = this.getConfigName(field);
      this.form[field] = config.inputLimiter.handleInput(value);
    },
    handlePaste(field, e) {
      const config = this.getConfigName(field);
      config.inputLimiter.handlePaste(e);
    },
    //选择日期时间
    receiveFromChild(data, type) {
      const TypeMap = {
        'YYYY-MM-DD HH:mm1': 'time1',
      };
      if (TypeMap[type]) {
        this.form[TypeMap[type]] = data;
      }
    },
    chooseImage() {
      this.currentItem = this.form
      this.$refs["imageInput"].click();
    },
    //选择执法人员
    handleInvestigatorChange({ identificationNumber, idField }) {
      if (idField && identificationNumber) {
        this.form[idField] = identificationNumber;
      }
    },
    // 选择图片
    async handleFileChange(event) {
      try {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = () => {
          this.currentItem.imageSrc = reader.result;
        };
        if (file) {
          this.isLoading = true;
          reader.readAsDataURL(file);
          setTimeout(() => {
            this.isLoading = false;
          }, 2000);

          const formData = new FormData();
          // 添加 file 属性，并指定文件名
          formData.append('file', file);

          // 设置 Content-Type 头部为 multipart/form-data
          const config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };

          const response = await axios.post('/api/related-file/uploadSign', formData, config);
          const { code, data, message } = response.data;
          if (code === '200') {
            if (data && data.url) {
              this.resultImgurl = data.url;
              this.resultImgname = data.name;
            } else {
              throw new Error('图片上传失败，请重试！');
            }
          } else {
            throw new Error(message || '图片上传失败，请重试！');
          }
          const url = `api/file/download/${this.resultImgurl}`;
          this.currentItem.imageSrc = url;
        }
      } catch (err) {
        this.$emit('updateSignImg', '', this.signType);
      }
    },
    // 选择单位
    selectUnitUpdateData(data) {
      data.forEach(item => {
        this.form[item.name] = item.value;
      })
    },
  }
}

</script>

<style scoped>
:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-select .el-input__wrapper) {
  display: block;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
